package ru.pbem.olympia.parser.text;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.ArrayUtils;
import ru.pbem.olympia.parser.ParseException;
import ru.pbem.olympia.parser.ReportParser;

import java.io.*;
import java.util.regex.Pattern;

/**
 * User: Roman Pavlov
 * Date: 15-Oct-2010
 * Time: 18:46:05
 */
public class G3ReportParser implements ReportParser {
    @Override
    public void parse(final InputStream in) throws ParseException {
        final BlockType[] types = BlockType.values();
        final BufferedReader lines = new BufferedReader(new InputStreamReader(in));
        try {
            ReportBlock currentBlock = null;
            String line = lines.readLine();
            while (line != null) {
                final BlockType currentType = currentBlock != null ? currentBlock.getType() : null;
                final BlockType newBlockType = getReportPartByHeader(line, currentType, types);
                if (newBlockType != null) {
                    System.out.println(currentBlock);
                    currentBlock = new ReportBlock(newBlockType);
                }
                if (currentBlock != null) {
                    currentBlock.addLine(line);
                }
                line = lines.readLine();
            }
            System.out.println(currentBlock);
        } catch (IOException e) {
            throw new ParseException(e);
        } finally {
            IOUtils.closeQuietly(lines);
        }
    }

    protected BlockType getReportPartByHeader(final CharSequence header, final BlockType currentPart, final BlockType[] types) {
        int startIndex = ArrayUtils.indexOf(types, currentPart);
        startIndex = startIndex < 0 ? 0 : startIndex;
        BlockType nextPart = null;
        for (int i = startIndex; i < types.length && nextPart == null; i++) {
            if (isLineMatched(header, types[i].getPatterns())) {
                nextPart = types[i];
            }
        }
        return nextPart;
    }

    protected boolean isLineMatched(final CharSequence line, final Iterable<Pattern> patterns) {
        for (final Pattern pattern : patterns) {
            if (pattern.matcher(line).matches()) {
                return true;
            }
        }
        return false;
    }

    public static void main(final String[] args) throws FileNotFoundException, ParseException {
        final InputStream is = new FileInputStream("D:\\Projects\\Olympia\\reports\\report7.txt");
        new G3ReportParser().parse(is);
    }
}
